package spring.module.scheduling;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * 定时任务配置
 *  
 * @author Lucky Yang
 */
@EnableScheduling
@Configuration
public class SchedulingConfig implements SchedulingConfigurer {
    private static final int POOL_SIZE = 10;
    
    // 可选方法
    public void configureTasks1(ScheduledTaskRegistrar taskRegistrar) {
        ThreadFactory threadFactory = new CustomizableThreadFactory("scheduled-pool-");
        // 设定一个长度10的定时任务线程池
        ExecutorService pool = new ScheduledThreadPoolExecutor(POOL_SIZE, threadFactory);

        taskRegistrar.setScheduler(pool);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();

        threadPoolTaskScheduler.setPoolSize(POOL_SIZE);
        threadPoolTaskScheduler.setThreadNamePrefix("scheduled-pool-");
        threadPoolTaskScheduler.initialize();

        scheduledTaskRegistrar.setTaskScheduler(threadPoolTaskScheduler);
    }    
}
